package com.hnkywl.sts.action.jhgl;

import com.hnkywl.sts.action.flow.assign.RegectTaskSingleBackWayCmd;
import com.hnkywl.sts.entity.jhgl.Cgxy;
import com.hnkywl.sts.entity.jhgl.Sfxy;
import com.hnkywl.sts.entity.jhgl.Xsxy;
import com.hnkywl.sts.entity.jhgl.Xy;
import com.hnkywl.sts.entity.sys.Bm;
import com.hnkywl.sts.entity.sys.Gncz;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.service.flow.FlowService;
import com.hnkywl.sts.service.jhgl.XyService;
import com.hnkywl.sts.service.sys.GnczService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.ReflectionUtils;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.jbpm.api.*;
import org.jbpm.api.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-4-2
 * Time: 上午9:49
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/jhgl/xygl")
public class XyglAction extends SimpleActionSupport {
    private XyService xyService;

    private YgService ygService;


    private FlowService flowService;

    private ProcessEngine processEngine;

    private TaskService taskService;

    private ExecutionService executionService;

    private HistoryService historyService;

    //协议ID
    private Long xyId;
    //分页组件 起始位置
    private int page;
    //分页组件 页面大小
    private int rows;
    //类型
    private Integer type;
    //终止原因
    private String zzyy;
    //协议实体
    private Xy xy;
    //采购协议实体
    private Cgxy cgxy;
    //销售协议实体
    private Xsxy xsxy;
    //三方协议实体
    private Sfxy sfxy;
    //员工实体
    private Yg yg;
    //当前登录员工的公司ID
    private Long gsId;

    private Long zggsId;
    //默认开始时间
    private Date startDate;
    //默认结束时间
    private Date endDate;

    //查询条件
    private Long gysId;

    private Long khId;

    private Long ssgsId;

    private String xyhm;

    private String spzt;

    private String result;

    private String taskId;

    private String content;

    private String processInstanceId;

    private String executionId;

    private List<String> types;

    private String xyType;

    private String tplx;

    private String tcgs;

    private Bm xyhmBm;

    //功能操作
    private List<Gncz> gnczList;
    private GnczService gnczService;

    @Action("xygl")
    public String xygl() {
        gnczList = gnczService.findGnczByJsAndUrl(request.getServletPath());
        yg = this.ygService.findYgDetail(YgService.getCurrentYg().getId());
        return SUCCESS;
    }


    @Action("xyglByProcessInstance")
    public void xyglByProcessInstance() {
        Xy xy;
        String processInstanceId;
        Execution execution = this.executionService.findExecutionById(executionId);
        if (execution != null) {
            xy = this.xyService.findXyDetailByProcessInstance(execution.getProcessInstance().getId());
            processInstanceId = execution.getProcessInstance().getId();
        } else {
            xy = this.xyService.findXyDetailByProcessInstance(executionId);
            processInstanceId = executionId;
        }
        Integer type;
        if (xy.getClass().getSimpleName().toUpperCase().equals("CGXY"))
            type = 1;
        else if (xy.getClass().getSimpleName().toUpperCase().equals("XSXY"))
            type = 2;
        else
            type = 3;
        String xyJson = "{'id':'" + xy.getId() + "','type':'" + type + "','businessNo':'" + xy.getXyhm() + "','processInstanceId':'" + processInstanceId + "'}";
        this.renderText(xyJson);
    }


    /**
     * 方法名:     协议查询
     * 功能描述:      查询协议（0：全部，1：采购协议，2：销售协议，3：三方协议）
     * 输入参数:    <@param xyId 协议ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("xyList")
    public void xyList() {
        if (type == 0)
            this.renderJson(this.xyService.findAllXy(xyhm, ssgsId, gysId, khId, spzt, page, rows));
        else if (type == 1)
            this.renderJson(this.xyService.findAllCgXy(xyhm, ssgsId, gysId, khId, spzt, page, rows));
        else if (type == 2)
            this.renderJson(this.xyService.findAllXsXy(xyhm, ssgsId, gysId, khId, spzt, page, rows));
        else
            this.renderJson(this.xyService.findAllSfXy(xyhm, ssgsId, gysId, khId, spzt, page, rows));
    }

    /**
     * 方法名:     控件combogrid协议查询
     * 功能描述:      查询协议（0：全部，1：采购协议，2：销售协议，3：三方协议）
     * 输入参数:    <@param xyId 协议ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("otherXyList")
    public void otherXyList() {
        this.renderJson(this.xyService.findAllXy(types, tplx, tcgs, ssgsId, spzt, page, rows));
    }

    @Action("simpleXsXyList")
    public void simpleXsXyList() {
        renderJson(this.xyService.findAllSimpleXsXy(page, rows));
    }

    /**
     * 方法名:     协议明细
     * 功能描述:      显示数据库协议名称
     * 输入参数:    <@param xyId 协议ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Actions({@Action("xygl_content"), @Action("xygl_detail")})
    public String xyglContent() {
        if (xyId != null) {
            xy = this.xyService.findXyDetail(xyId);
            if (xy instanceof Cgxy) {
                type = 1;
                cgxy = (Cgxy) xy;
            } else if (xy instanceof Xsxy) {
                type = 2;
                xsxy = (Xsxy) xy;
            } else if (xy instanceof Sfxy) {
                type = 3;
                sfxy = (Sfxy) xy;
            }
        } else {
            this.startDate = initStartDate();
            this.endDate = initEndDate(startDate);
        }
        zggsId = YgService.getCurrentYgZgGsId();
        gsId = YgService.getCurrentYgGsId();
        yg = YgService.getCurrentYg();
        return SUCCESS;
    }

    private Date initStartDate() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(cal.YEAR);
        int month = cal.get(cal.MONTH);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month + 1);
        cal.set(Calendar.DATE, 1);
        return cal.getTime();
    }

    private Date initEndDate(Date startDate) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        cal.set(Calendar.YEAR, cal.get(cal.YEAR) + 1);
        return cal.getTime();
    }

    /**
     * 方法名:     保存协议
     * 功能描述:      保存数据库协议
     * 输入参数:    <@param xy 协议>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("add_xy")
    public void addXy() {
        try {
            initXy(xy);
            if (type == 1) {
                initCgXy(cgxy);
                PropertyUtils.copyProperties(cgxy, xy);
                this.xyService.saveXy(cgxy);
            } else if (type == 2) {
                initXsxy(xsxy);
                PropertyUtils.copyProperties(xsxy, xy);
                this.xyService.saveXy(xsxy);
            } else if (type == 3) {
                initSfxy(sfxy);
                PropertyUtils.copyProperties(sfxy, xy);
                this.xyService.saveXy(sfxy);
            }
            renderText("{\"statusCode\":\"200\", \"message\":\"保存协议成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 方法名:     保存协议
     * 功能描述:      保存数据库协议
     * 输入参数:    <@param xy 协议>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("edit_xy")
    public void editXy() {
        try {
            initXy(xy);
            if (type == 1) {
                PropertyUtils.copyProperties(cgxy, xy);
                Xy clone = this.xyService.findXyDetail(cgxy.getId());
                String xyhm = clone.getXyhm();
                ReflectionUtils.getInstance(clone, cgxy);
                initCgXy((Cgxy) clone);
                this.xyService.editXy(clone, xyhm);
            } else if (type == 2) {
                PropertyUtils.copyProperties(xsxy, xy);
                Xy clone = this.xyService.findXyDetail(xsxy.getId());
                String xyhm = clone.getXyhm();
                ReflectionUtils.getInstance(clone, xsxy);
                initXsxy((Xsxy) clone);
                this.xyService.editXy(clone, xyhm);
            } else if (type == 3) {
                PropertyUtils.copyProperties(sfxy, xy);
                Xy clone = this.xyService.findXyDetail(sfxy.getId());
                String xyhm = clone.getXyhm();
                ReflectionUtils.getInstance(clone, sfxy);
                initSfxy((Sfxy) clone);
                this.xyService.editXy(clone, xyhm);
            }
            renderText("{\"statusCode\":\"200\", \"message\":\"保存协议成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    private void initXy(Xy xy) {
        if (xy.getFkfs() != null && xy.getFkfs().getId() == null) {
            xy.setFkfs(null);
        }
        if (xy.getDbf() != null && xy.getDbf().getId() == null) {
            xy.setDbf(null);
        }
        xy.setXyzt("ybc");
    }

    private void initCgXy(Cgxy cgxy) {
        if (cgxy.getGys() != null && cgxy.getGys().getId() == null) {
            cgxy.setGys(null);
        }
    }

    private void initXsxy(Xsxy xsxy) {
        if (xsxy.getKh() != null && xsxy.getKh().getId() == null) {
            xsxy.setKh(null);
        }
        if (xsxy.getHkjsfs() != null && xsxy.getHkjsfs().getId() == null) {
            xsxy.setHkjsfs(null);
        }
    }

    private void initSfxy(Sfxy sfxy) {
        if (sfxy.getGys() != null && sfxy.getGys().getId() == null) {
            sfxy.setGys(null);
        }
        if (sfxy.getKh() != null && sfxy.getKh().getId() == null) {
            sfxy.setKh(null);
        }
        if (sfxy.getHkjsfs() != null && sfxy.getHkjsfs().getId() == null) {
            sfxy.setHkjsfs(null);
        }
    }

    /**
     * 方法名:     提交协议
     * 功能描述:      提交协议到法务部审核
     * 输入参数:    <@param xyId 协议ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("commit_xy")
    public void commitXy() {
        try {
            xy = this.xyService.findXyDetail(xyId);
            if (this.flowService.checkFlowStart("协议流程")) {
                String contain = StringUtils.EMPTY;
                if (xy.getCreateDepartment().getId() == 30 || xy.getCreateDepartment().getId() == 26
                        || xy.getCreateDepartment().getId() == 27 || xy.getCreateDepartment().getId() == 28
                        || xy.getCreateDepartment().getId() == 29 || xy.getCreateDepartment().getId() == 8131
                        || xy.getCreateDepartment().getId() == 8132
                        || xy.getCreateDepartment().getId() == 8133
                        || xy.getCreateDepartment().getId() == 8134)
                    contain = "贸易部";
                String processInstanceId = this.flowService.regTask(xy.getProcessInstanceId(), "协议流程", contain);
                xy.setProcessInstanceId(processInstanceId);
                xy.setXyzt("ytj");
            } else
                xy.setXyzt("ysp");
            this.xyService.editXy(xy, xy.getXyhm());

            renderText("{\"statusCode\":\"200\", \"message\":\"提交协议成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    /**
     * 方法名:     删除协议
     * 功能描述:      删除数据库协议
     * 输入参数:    <@param xyId 协议ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("delete_xy")
    public void delete_xy() {
        try {
            Xy xy = this.xyService.deleteXy(xyId);
            this.flowService.delPorcessInstance(xy.getProcessInstanceId());
            renderText("{\"statusCode\":\"200\", \"message\":\"删除协议成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 方法名:     履约协议
     * 功能描述:      履约数据库协议
     * 输入参数:    <@param xyId 协议ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("agree_xy")
    public void agree_xy() {
        try {
            this.xyService.agreeXy(xyId, YgService.getCurrentYg());
            renderText("{\"statusCode\":\"200\", \"message\":\"履约协议成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 方法名:     终止协议
     * 功能描述:      终止数据库协议
     * 输入参数:    <@param xyId 协议ID>
     * 异常:      <RuntimeException  Exception>
     * 创建人:     lingyun
     * 创建日期:   13-3-7上午11:47
     * 修改人:     lingyun
     * 修改日期:   13-3-7上午11:47
     */
    @Action("stop_xy")
    public void stop_xy() {
        try {
            this.xyService.stopXy(xyId, YgService.getCurrentYg(), zzyy);
            renderText("{\"statusCode\":\"200\", \"message\":\"履约协议成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    @Action(value = "examineTask")
    public void examineTask() {
        if (this.result.equals("审核")) {
            Map<String, Object> var = new HashMap<String, Object>();
            var.put("owner", YgService.getCurrentYg().getId());
            var.put("opera", YgService.getCurrentYgGs() + "--" + YgService.getCurrentYgName());
            var.put("result", "审核通过");
            var.put("content", content);
            var.put("time", new Date());
            Task currentTask = this.taskService.getTask(taskId);
            String executionId = currentTask.getExecutionId();
            executionService.createVariables(executionId, var, true);
            var.put("status", result);

            Execution execution = this.executionService.findExecutionById(executionId);
            Xy xy = xyService.findXyDetailByProcessInstance(execution.getProcessInstance().getId());
            if (xy.getCreateDepartment().getId() == 30 || xy.getCreateDepartment().getId() == 26
                    || xy.getCreateDepartment().getId() == 27 || xy.getCreateDepartment().getId() == 28
                    || xy.getCreateDepartment().getId() == 29|| xy.getCreateDepartment().getId() == 8131
                    || xy.getCreateDepartment().getId() == 8132
                    || xy.getCreateDepartment().getId() == 8133
                    || xy.getCreateDepartment().getId() == 8134)
                var.put("contain", "贸易部");
            else
                var.put("contain", StringUtils.EMPTY);
            this.taskService.completeTask(taskId, var);

//            Execution execution = this.executionService.findExecutionById(executionId);
//            if (execution != null) {
//                Xy xy = xyService.findXyDetailByProcessInstance(execution.getProcessInstance().getId());
            if (xy.getXyzt().equals("ybc")) {
                xy.setXyzt("ytj");
                xyService.editXy(xy, xy.getXyhm());
            }
//            }
        } else {
            String result = processEngine.execute(new RegectTaskSingleBackWayCmd(taskId, content));
            if (result.equals("change")) {
                //修改状态  ytj--->ybc
                String executionId = this.historyService.createHistoryTaskQuery().taskId(taskId).uniqueResult().getExecutionId();
                Execution execution = this.executionService.findExecutionById(executionId);
                Xy xy = xyService.findXyDetailByProcessInstance(execution.getProcessInstance().getId());
                xy.setXyzt("ybc");
                xyService.editXy(xy, xy.getXyhm());
            }
        }
        this.renderText("{\"statusCode\":\"200\", \"message\":\"审核流程成功\"}");
    }

    public List<String> getTypes() {
        return types;
    }

    public void setTypes(List<String> types) {
        this.types = types;
    }

    public Long getXyId() {
        return xyId;
    }

    public void setXyId(Long xyId) {
        this.xyId = xyId;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public String getZzyy() {
        return zzyy;
    }

    public void setZzyy(String zzyy) {
        this.zzyy = zzyy;
    }

    public Yg getYg() {
        return yg;
    }

    public void setYg(Yg yg) {
        this.yg = yg;
    }

    public Long getGsId() {
        return gsId;
    }

    public void setGsId(Long gsId) {
        this.gsId = gsId;
    }

    public Long getZggsId() {
        return zggsId;
    }

    public void setZggsId(Long zggsId) {
        this.zggsId = zggsId;
    }

    public Xy getXy() {
        return xy;
    }

    public void setXy(Xy xy) {
        this.xy = xy;
    }

    public Cgxy getCgxy() {
        return cgxy;
    }

    public void setCgxy(Cgxy cgxy) {
        this.cgxy = cgxy;
    }

    public Xsxy getXsxy() {
        return xsxy;
    }

    public void setXsxy(Xsxy xsxy) {
        this.xsxy = xsxy;
    }

    public Sfxy getSfxy() {
        return sfxy;
    }

    public void setSfxy(Sfxy sfxy) {
        this.sfxy = sfxy;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Long getGysId() {
        return gysId;
    }

    public void setGysId(Long gysId) {
        this.gysId = gysId;
    }

    public Long getKhId() {
        return khId;
    }

    public void setKhId(Long khId) {
        this.khId = khId;
    }

    public Long getSsgsId() {
        return ssgsId;
    }

    public void setSsgsId(Long ssgsId) {
        this.ssgsId = ssgsId;
    }

    public String getXyhm() {
        return xyhm;
    }

    public void setXyhm(String xyhm) {
        this.xyhm = xyhm;
    }

    public String getSpzt() {
        return spzt;
    }

    public void setSpzt(String spzt) {
        this.spzt = spzt;
    }

    public String getProcessInstanceId() {
        return processInstanceId;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getExecutionId() {
        return executionId;
    }

    public void setExecutionId(String executionId) {
        this.executionId = executionId;
    }

    public void setProcessInstanceId(String processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    public String getXyType() {
        return xyType;
    }

    public void setXyType(String xyType) {
        this.xyType = xyType;
    }

    public Bm getXyhmBm() {
        return xyhmBm;
    }

    public void setXyhmBm(Bm xyhmBm) {
        this.xyhmBm = xyhmBm;
    }

    public String getTplx() {
        return tplx;
    }

    public void setTplx(String tplx) {
        this.tplx = tplx;
    }

    public List<Gncz> getGnczList() {
        return gnczList;
    }

    public void setGnczList(List<Gncz> gnczList) {
        this.gnczList = gnczList;
    }

    public String getTcgs() {
        return tcgs;
    }

    public void setTcgs(String tcgs) {
        this.tcgs = tcgs;
    }

    @Autowired
    public void setXyService(XyService xyService) {
        this.xyService = xyService;
    }

    @Autowired
    public void setYgService(YgService ygService) {
        this.ygService = ygService;
    }

    @Autowired
    public void setFlowService(FlowService flowService) {
        this.flowService = flowService;
    }

    @Autowired
    public void setExecutionService(@Qualifier("executionService") ExecutionService executionService) {
        this.executionService = executionService;
    }

    @Autowired
    public void setTaskService(@Qualifier("taskService") TaskService taskService) {
        this.taskService = taskService;
    }

    @Autowired
    public void setProcessEngine(@Qualifier("processEngine") ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    @Autowired
    public void setHistoryService(@Qualifier("historyService") HistoryService historyService) {
        this.historyService = historyService;
    }

    @Autowired
    public void setGnczService(GnczService gnczService) {
        this.gnczService = gnczService;
    }
}
